<template>
  <div class="login">
    <el-card class="login-form">
      <template #header>
        <h3 class="card-header">{{ CONFIGS.LoginTitle }}</h3>
      </template>
      <el-form ref="loginForm" :model="form" :rules="rules" @keydown.enter.native="SubmitLogon(loginForm)">
        <el-form-item label-position="right" prop="Username">
          <el-input v-model="form.Username" :placeholder='t("placeholder.inputUsername")'>
            <template #prefix>
              <el-icon>
                <UserFilled />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label-position="right" prop="Password">
          <el-input v-model="form.Password" type="password" :placeholder='t("placeholder.inputPassword")'>
            <template #prefix>
              <el-icon>
                <Lock />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item v-if="isCode" label-position="right" prop="Code">
          <el-input v-model="form.Code" :placeholder='t("placeholder.inputCode")'>
            <template #prefix>
              <el-icon>
                <Key />
              </el-icon>
            </template>
            <template #append v-if="bind.isShowQrCode">
              <el-button @click="bind.modal = true">显示二维码</el-button>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="card-footer">
          <el-button type="primary" class="w__100" :loading="loading" @click="SubmitLogon(loginForm)">
            {{ t("button.logon") }}
          </el-button>
        </div>
      </template>
    </el-card>
    <el-dialog v-model="bind.modal" :title="t('rbacManager.CreateGoogleAuth')" @close="CloseBind" width="300">
      <span id="qrcode" class="qrcode" ref="qrcodeRef"></span>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref, nextTick } from "vue";
import { ElNotification, type FormInstance, type FormRules } from "element-plus";
import { setToken } from "@/library/utils";
import { PortalApi } from "@/api/portal";
import { useRouter } from "vue-router";
import { useStorage } from "@/library/storage";
import useI18n from "@/hooks/useI18n";
import { CONFIGS, HOME_URL } from "@/config"
import { CreateBindQrCode, getTimeState } from "@/library/utils/tools"
import { useStore, moduleActionDispatchMap } from "@/hooks/store/useStore";
import * as types from "./types"

const t = useI18n();
const { push } = useRouter();

const { dispatch } = useStore();
const { app, user } = moduleActionDispatchMap
const { setStorage } = useStorage("localStorage");

const loginForm = ref<FormInstance>();

const form = reactive<types.RuleForm>({
  Username: "",
  Password: "",
  Code: ""
});

const bindParmas = reactive<types.BindParams>({
  title: CONFIGS.LoginTitle,
  name: ''
})

const bind = reactive<types.BindState>({
  modal: false,
  isShowQrCode: false,
  params: { ...bindParmas }
})

const loading = ref(false)
const isCode = ref(false)
const qrcodeRef = ref<HTMLElement>()

const rules: FormRules<types.RuleForm> = {
  Username: [{ required: true, message: t("placeholder.inputUsername"), trigger: "blur" }],
  Password: [{ required: true, message: t("placeholder.inputPassword"), trigger: "blur" }],
  Code: [{ required: true, message: t('placeholder.inputCode'), trigger: "blur" }]
};

// 登录
const SubmitLogon = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;

  formEl.validate((valid) => {
    if (!valid) { return }

    loading.value = true
    bind.params.name = form.Username

    PortalApi.Login(form)
      .then(({ Data }) => {
        // 未开启谷歌验证, 正常登录
        dispatch(user.setUser, Data.User)
        setToken({ token: Data.Token });
        setStorage("user", Data.User);
        push({ path: HOME_URL });

        let username = Data.User.Username

        ElNotification({
          title: getTimeState(),
          message: `欢迎登录 ${username}`,
          type: "success",
          duration: 3000
        });
      })
      .catch(({ Code, Data }) => {
        // 开启谷歌验证, 但未创建谷歌验证码
        if (Code === 2) {
          bind.modal = true
          isCode.value = true
          bind.isShowQrCode = true

          let SystemName = bind.params.title + "-" + process.env.VUE_APP_FLAG
          nextTick(() => {
            CreateBindQrCode(qrcodeRef.value!, bind.params.name, SystemName, Data, [200, 200])
          })
        }

        // 已创建谷歌验证码, 附加验证码输入框
        else if (Code === 3) {
          isCode.value = true
        }
      })
      .finally(() => {
        loading.value = false
      })
  });
};

const CloseBind = () => {
  bind.modal = false
  nextTick(() => {
    bind.params = { ...bindParmas }
  })
}

onMounted(() => {
  dispatch(app.init, "init");
});

</script>

<style lang="scss" scoped>
.login {
  width: 100%;
  height: 100vh;
  background: url("@/assets/images/background.jpg");
  background-size: cover;
  background-position: center;
  position: relative;

  &-form {
    width: 320px;
    position: absolute;
    right: 10vw;
    top: 35vh;
    background: #fff;

    .el-card {
      &__header {
        margin: 0;
        padding: 0;

        h3 {
          padding: 0;
          margin: 0;
        }
      }

      &__footer {
        margin: 0;
        padding: 0;

        .w {
          &__100 {
            width: 100%;
          }
        }
      }
    }
  }
}

.qrcode {
  width: 200px;
  height: 200px;
  padding: 8px;
  border: 1px solid #ddd;
  display: inline-block;
  position: relative;
  left: calc(50% - 110px);
}

.el-dialog__body {
  text-align: center;
}
</style>
